package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户")
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    UserService userService;

    @GetMapping("/shop/status")
    @ApiOperation("查看店铺运行状态")
    public Result status(){
        log.info("查看店铺运行状态");
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Integer s = (Integer) valueOperations.get("SHOP_STATUS");
        if(s==null){
            s = 0;
        }
        return Result.success(s);
    }
    @PostMapping("/user/login")
    @ApiOperation("用户登陆")
    public Result login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户端登录接口:{}",userLoginDTO);

        //1.调用业务进行微信登录，返回登录User对象
        User user = userService.login(userLoginDTO);

        //2.下发令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        //3.封装数据返回
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }
}
